package com.lsh.ofc.provider.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsh.base.common.exception.BusinessException;
import com.lsh.base.common.model.CommonResult;
import com.lsh.ofc.api.dto.SupplierDTO;
import com.lsh.ofc.api.dto.SupplierSaasDTO;
import com.lsh.ofc.api.service.supplier.SupplierService;
import com.lsh.ofc.core.entity.MeipiCustomer;
import com.lsh.ofc.core.entity.OfcSupplier;
import com.lsh.ofc.core.enums.*;
import com.lsh.ofc.core.exception.EC;
import com.lsh.ofc.core.service.SaasMeipiCustomerService;
import com.lsh.ofc.core.service.SupplierConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;

/**
 * Project Name: lsh-ofc
 *
 * @author peter
 * @date 18/11/26
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Service(protocol = "dubbo", validation = "true", timeout = 10000)
@Slf4j
public class SupplierServiceImpl implements SupplierService {

    @Autowired
    private SaasMeipiCustomerService saasMeipiCustomerService;

    @Resource
    private SupplierConfigService supplierConfigService;

    @Override
    public CommonResult<Boolean> addCloudSupplier(SupplierDTO supplierDTO) throws BusinessException {
        CommonResult<Boolean> commonResult;

        log.info("添加OFC供货商信息，参数：{}", JSON.toJSONString(supplierDTO));
        try {
            this.validateParam(supplierDTO);
            // TODO: 2019-11-06
            OfcSupplier ofcSupplier = supplierConfigService.findSupplier(supplierDTO.getSupplierId(), supplierDTO.getCode(), supplierDTO.getSupplierGroup(), SupplierOrg.LSH.getValue(), supplierDTO.getRegionCode(), supplierDTO.getSupplierDc());

            if (ofcSupplier != null) {
                return CommonResult.success(true);
            }
//
//            //添加新的供商id 添加数据库
            int time = (int) (System.currentTimeMillis() / 1000);
            OfcSupplier insert = new OfcSupplier();

            insert.setId(null);
            insert.setCode(supplierDTO.getCode());
            insert.setSupplierGroup(supplierDTO.getSupplierGroup());
            insert.setSupplierOrg(SupplierOrg.LSH.getValue());
            insert.setRegionCode(supplierDTO.getRegionCode());
            insert.setValid(Valid.enable.getValue());
            // 替换supplyId
            insert.setSupplierId(supplierDTO.getSupplierId());
            insert.setCreateTime(time);
            insert.setUpdateTime(time);
            insert.setValid(Valid.enable.getValue());
            int flag = supplierConfigService.save(insert);
            commonResult = CommonResult.success(true);
        } catch (BusinessException ex) {
            log.error("添加OFC供货商信息异常", ex);
            commonResult = CommonResult.error(ex.getMessage(), false);
        } catch (Throwable t) {
            log.error("添加OFC供货商信息异常：{}", t);
            commonResult = CommonResult.error("业务处理错误", false);
        }

        return commonResult;
    }

    /**
     * 创建SO订单
     *
     * @param supplierDTO
     * @return
     * @throws BusinessException
     */
    @Override
    public CommonResult<Boolean> addSaasSupplier(SupplierSaasDTO supplierDTO) throws BusinessException {
        CommonResult<Boolean> commonResult;

        log.info("saas添加OFC供货商信息，参数：{}", JSON.toJSONString(supplierDTO));
        try {
//            this.validateParam(supplierDTO);
            // TODO: 2019-11-06
            OfcSupplier ofcSupplier = supplierConfigService.findSupplier(supplierDTO.getSupplierId(), supplierDTO.getCode(), supplierDTO.getSupplierGroup(), SupplierOrg.LSH.getValue(), supplierDTO.getRegionCode(), supplierDTO.getSupplierDc());
            if (ofcSupplier != null) {
                return CommonResult.success(true);
            }

            //添加新的供商id 添加数据库
            int time = (int) (System.currentTimeMillis() / 1000);
            OfcSupplier insert = new OfcSupplier();

            insert.setCode(supplierDTO.getCode());
            insert.setRegionCode(supplierDTO.getRegionCode());
            insert.setVenderId(supplierDTO.getVenderId());
            insert.setSupplierOrg(supplierDTO.getSupplierOrg());
            insert.setSupplierId(supplierDTO.getSupplierId());

            JSONObject extJson = JSON.parseObject(supplierDTO.getExt());
            JSONObject config = new JSONObject();
            Integer saleModel = extJson.getInteger("saleModel");
            Integer deliveryType = extJson.getInteger("deliveryType");
            Integer supplierGroup = extJson.getInteger("supplierGroup");
            Integer collaborativeFlag = extJson.getInteger("collaborativeFlag");
            String collaborativeDc = extJson.getString("collaborativeDc");

            config.put("saleModel", saleModel);
            config.put("deliveryType", deliveryType);
            config.put("wmsPath", extJson.getString("queryStockPath"));
            config.put("ownerId", extJson.getString("ownerId"));
            config.put("customerId", extJson.getString("ownerId"));
            config.put("zone", "BX04");
            config.put("tuPrefix", "1");
            config.put("isForceCancel", "0");
            config.put("vsb", "02");
            config.put("mkt", "4");
            config.put("orderSource", "2");
            config.put("cmp", "S007");
            config.put("soOrderType", "2");
            config.put("cusType", 5);
            config.put("usr", "0000151004");
            config.put("wumartFill", WumartFill.IS_NOT_WUMARKT_FILL.getValue());
            if(deliveryType == 3){
                config.put("wgFill", 0);
            }else{
                config.put("wgFill", collaborativeFlag);
            }

            insert.setSupplierGroup(supplierGroup + "");
            insert.setSupplierDc(supplierDTO.getSupplierDc());
            insert.setWarehouseCode(supplierDTO.getSupplierDc());
            insert.setWarehouseName("SAAS-" + supplierDTO.getSupplierDc());
            if(collaborativeFlag == 1){
                insert.setSupplierDc(collaborativeDc);
                insert.setWarehouseCode(collaborativeDc);
                insert.setWarehouseName(supplierDTO.getCode() + "-" + collaborativeDc);
            }

            insert.setConfig(config.toJSONString());
            insert.setCreateTime(time);
            insert.setUpdateTime(time);

            insert.setFulfillChannel(FulfillChannel.SAAS_PSI.getValue());
            insert.setFulfillWms(FulfillWms.LSH.getValue());
            insert.setValid(Valid.enable.getValue());
            if (saleModel == 2 && deliveryType == 4) {
                insert.setFulfillChannel(FulfillChannel.SAAS_OFC.getValue());
                insert.setFulfillWms(FulfillWms.NONE.getValue());
            } else if (saleModel == 2 && deliveryType == 3) {
                insert.setFulfillChannel(FulfillChannel.SAAS_PSI.getValue());
                insert.setFulfillWms(FulfillWms.LSH.getValue());
            }else if (saleModel == 1 && deliveryType == 3) {
                insert.setFulfillChannel(FulfillChannel.SAAS_PSI.getValue());
                insert.setFulfillWms(FulfillWms.LSH.getValue());
            }

            int flag = supplierConfigService.save(insert);
            if (flag > 0) {
                this.addSaasCostomer(insert);
                commonResult = CommonResult.success(true);
            } else {
                commonResult = CommonResult.error("数据库添加失败", true);
            }
        } catch (BusinessException ex) {
            log.error("添加OFC供货商信息异常", ex);
            commonResult = CommonResult.error(ex.getMessage(), false);
        } catch (Throwable t) {
            log.error("添加OFC供货商信息异常：{}", t);
            commonResult = CommonResult.error("业务处理错误", false);
        }

        return commonResult;
    }

    /**
     *
     * @param supplier
     */
    private void addSaasCostomer(OfcSupplier supplier) {

        try {
            MeipiCustomer countFilter = new MeipiCustomer();
            countFilter.setRegionCode(supplier.getRegionCode());
            int count = saasMeipiCustomerService.count(countFilter);
            if (count > 1000) {
                return;
            }
            MeipiCustomer customer = saasMeipiCustomerService.getMaxMeipiCodeByType(5);
            if (customer == null) {
                return;
            }
            String custCode = customer.getCustCode();
            int custCodeInt = Integer.valueOf(custCode);
            for (int i = 0; i <= 50; i++) {
                custCodeInt++;
                String custCodeStr = custCodeInt + "";
                if (custCodeStr.length() <= 9) {
                    custCodeStr = "0" + custCodeStr;
                }

                saasMeipiCustomerService.addSaasMpCust(supplier.getRegionCode(), 5, custCodeStr, supplier.getVenderId());
            }
        } catch (BusinessException e) {
            log.error("supplier 插入美批用户失败", e);
        } catch (Exception e) {
            log.error("supplier 插入美批用户失败2", e);
        }
    }

    public static void main(String[] args) {
        String ds = "0881004652";

        int cout = Integer.valueOf(ds);
        System.out.printf(cout + 1 + "");
    }

    /**
     * 校验参数
     *
     * @param supplierDTO
     */
    private void validateParam(SupplierDTO supplierDTO) {
        if (StringUtils.isAnyEmpty(supplierDTO.getCode(), supplierDTO.getSupplierDc())) {
            throw EC.ERROR_PARAMS.exception("code, supplierDc不正确");
        }

        if (supplierDTO.getRegionCode() == null || supplierDTO.getRegionCode().intValue() == 0) {
            throw EC.ERROR_PARAMS.exception("regionCode 不正确");
        }

        if (supplierDTO.getSupplierId() == null || supplierDTO.getSupplierId().intValue() == 0) {
            throw EC.ERROR_PARAMS.exception("supplierId 不正确");
        }
    }
}
